package com.hunan.api.catv.interceptor;

import lombok.extern.java.Log;
import org.slf4j.MDC;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*")
@Log
public class LogRequestIdFilter implements Filter {

    public static final String REQUEST_ID_KEY = "X-Request-Id";

    public static String getRequestId(HttpServletRequest request) {
        String requestId = null;
        String parameterRequestId = request.getParameter(REQUEST_ID_KEY);
        String headerRequestId = request.getHeader(REQUEST_ID_KEY);

        if (parameterRequestId == null && headerRequestId == null) {
            log.info("request parameter 和header 都没有requestId入参");
            requestId = UUID.randomUUID().toString();
        } else {
            requestId = parameterRequestId != null ? parameterRequestId : headerRequestId;
        }
        //requestIdThreadLocal.set(requestId);
        MDC.put(REQUEST_ID_KEY, requestId);
        return requestId;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //log.info("============== filter ==============");
        LogRequestIdFilter.getRequestId((HttpServletRequest) request);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        MDC.remove(REQUEST_ID_KEY);
    }
}
